<?php namespace Common\Model;
use Hdphp\Model\Model;
//订单管理模型
class Uorders extends Model{
	//指定表明固定写法
	protected $table = "uorders";
	//自动验证，固定写法
	protected $validate = array(
		//array(字段名,验证方法,错误信息,验证条件,验证时间)
		//array('addresses','required','用户地址必须填写',3,3),
		
	);
	
	//用户增加新地址
	public function newstore(){
	    //因为表单中没有addresses，所以在自动验证之前就要把地址组合好
		$_POST['addresses'] = Q('post.province') . ',' . Q('post.city') . ',' . Q('post.town') . ',' . Q('post.details');
		//添加到地址表
			$address = new \Common\Model\Address;
			$datas = array(
				'addresses' => $_POST['addresses'],
				'cardcodes' => $_POST['poscodes'],
				'taketime'  => $_POST['taketime'],
				'telephone' => $_POST['telephone'],
				'customer'  => $_POST['customer'],
				//是否为默认地址，1为默认地址
				'statu'     => 0,
				'user_uid'  => $_SESSION['uid'],
				
			);
			//地址表自增主键，订单表里使用
			$numb = $address->add($datas);
			return $numb;
	}
	
	//store方法是自己定义如果自动验证通过添加到数据库
	public function store(){			
		//地址表自增主键，订单表里使用
		//添加到订单表
		if($this->create()){			
			$this->data['ordernum'] = $this->number();
			$this->data['totalprice'] = isset($_SESSION['cart']['total']) ? $_SESSION['cart']['total'] : 0;
			$this->data['buildtime'] = time();
			//订单状态，是否付款
			$this->data['status'] = 0;
			$this->data['user_uid'] = $_SESSION['uid'];
			//$this->data['address_did'] = $numb;
			//订单表自增主键，订单列表里使用
			$num=$this->add();
			
			//添加到订单列表
			$orderlist = new \Common\Model\Orderlist;
			foreach ($_SESSION['cart']['goods'] as $k => $v) {				
				$data=array(
					'buynum'    => $v['num'],
					'remark'    => $v['options']['color'] . ',' . $v['options']['size'],
					'goods_gid' => $v['id'],
					'subtotal'  =>$v['total'],
					'order_oid' => $num,
					
				);
				$orderlist->add($data);
			}
			return true;
		}else{
			return false;
		}
	}
	
	//随机生成订单号
	public function number($length=8){
		 $chars = "0123456789abcdefghijklmnopqrstuvwxyz";
		 $num = '';
		 $char_len = strlen($chars);
		 for($i=0;$i<$length;$i++){
		  $loop = mt_rand(0, ($char_len-1));
		  //将这个字符串当作一个数组，随机取出一个字符，并循环拼接成你需要的位数
		  $num .= $chars[$loop];
		 }
		return date('Ymd') .$num;
		
	}
	
}





?>	
	
	
	
	
	
	
	